<?php

namespace App\Http\Admin\Services;


use App\Api\Exceptions\BusinessException;
use App\Http\Admin\HelpsTraits\DataTransform;
use App\Models\Admin\AdminDepartment;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Role;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;


class AdminUserService extends BaseService
{
    use DataTransform;

    /**
     * 用户是否存在
     * @param string $account 账号
     * @return null
     */
    public function isExistUser(string $account)
    {
        return AdminUser::where('account', $account)->first() ?? null;
    }

    /**
     * 校验密码
     * @param string $account 账户名
     * @param string $password 密码
     * @return mixed
     * @throws BusinessException
     */
    public function checkUser(string $account, string $password): mixed
    {

        $user = $this->isExistUser($account);
        if (!$user || !Hash::check($password, $user['password'])) {
            $this->throwBusinessException(info: '帐号或密码不匹配，请重新输入');
        } else {
            return $user;
        }
    }

    /**
     * 判断部门是否存在
     * @param array $data 用户数据
     * @return void
     */
    public function isExistDepartment(array $data)
    {
        if (isset($data['department_id']) && !empty($data['department_id'])) {
            AdminDepartment::findOrFail($data['department_id']);
        }
    }

    /**
     * 邮箱是否已存在
     * @param array $data 用户数据
     * @return void
     * @throws BusinessException
     */
    public function emailIsExist(array $data)
    {
        if ($this->isExist($data, 'email') && AdminUser::where('email', $data['email'])->exists()) {
            $this->throwBusinessException(info: '邮箱已存在');
        };
    }

    /**
     * 手机是否已存在
     * @param array $data 用户数据
     * @return void
     * @throws BusinessException
     */
    public function phoneIsExist(array $data)
    {
        if ($this->isExist($data, 'phone') && AdminUser::where('phone', $data['phone'])->exists()) {
            $this->throwBusinessException(info: '手机已存在');
        };
    }

    /**
     * 更新手机校验
     * @param array|Authenticatable $user
     * @param array $data
     * @return void
     * @throws BusinessException
     */
    public function phoneUpdateCheck(array|Authenticatable $user, array $data)
    {
        if ($this->isExist($data, 'phone') && $user['phone'] != $data['phone'] && AdminUser::where('phone', $data['phone'])->exists())
            $this->throwBusinessException(info: '手机已存在');
    }

    /**
     * 更新邮箱校验
     * @param array|Authenticatable $user
     * @param array $update_data
     * @return void
     * @throws BusinessException
     */
    public function emailUpdateCheck(array|Authenticatable $user, array $update_data)
    {
        if ($this->isExist($update_data, 'email') && $user['email'] != $update_data['email'] && AdminUser::where('email', $update_data['email'])->exists())
            $this->throwBusinessException(info: '邮箱已存在');
    }

    /**
     * 更新密码
     * @param $update_data
     * @return void
     */
    public function updatePassword(&$update_data)
    {
        if ($this->isExist($update_data, 'password'))
            $update_data['password'] = Hash::make($update_data['password']);
    }

    /**
     * 添加角色
     * @param AdminUser $user 用户名
     * @param array $ids
     * @return AdminUser
     */
    public function assignRoles(AdminUser $user, array $ids): AdminUser
    {
        return $user->assignRole(Role::whereIn('id', $ids)->get());
    }



    /***********上面为辅助业务方法，下面主要业务方法************/


    /**
     * 获取当前用户所有的信息
     * @param AdminUser $user
     * @return array
     */
    public function getSelfInfo(AdminUser $user): array
    {
        return ['user_id' => $user['id'], 'user_name' => $user['account'], 'avatar' => $user['avatar'], 'email' => $user['email'], 'nick_name' => $user['nick_name'], 'phone' => $user['phone'], 'user_role' => $user->getRoleNames()];
    }

    /**
     * 获取用户的菜单
     * @param AdminUser $user
     * @return array
     */
    public function getUserPermMenus(AdminUser $user)
    {
//        return $user->getAllPermissions();
//        return  $this->getTree($user->getAllPermissions()->toArray());
        $result['routes'] = self::permDataTransform($this->getTree($user->getAllPermissions()->where('type', '!=', 2)->toArray()));
        $result['home'] = 'dashboard_workbench';
        return $result;
//        return config('test-data.web-route');
    }


    /**
     * 获取用户所有的权限
     * @param AdminUser $user
     * @return \Illuminate\Support\Collection
     */
    public function getUserPerms(AdminUser $user): \Illuminate\Support\Collection
    {
        return $user->getAllPermissions()->where('type', 2);
    }

    /**
     * 用户列表
     * @param array $params
     * @return array|bool|null
     */

    public function list(array $params): array|bool|null
    {
        return $this->page($params, AdminUser::with('roles:name')) ?? null;
    }


    /**
     * 指定ID的用户详情
     * @param int $id
     * @return mixed
     */
    public function info(int $id): mixed
    {
        $user = AdminUser::findOrFail($id);
        $user['roles'] = $user->roles->makeHidden(['pivot',  'guard_name']);
        return $user;
    }


    /**
     * 创建用户
     * @param $user_data // 用户表单
     * @return void
     * @throws BusinessException
     * @throws \Throwable
     */
    public function createUser(array $user_data)
    {
        $this->isExistDepartment($user_data); // 校验部门
        $this->emailIsExist($user_data); // 校验邮箱
        $this->phoneIsExist($user_data); // 校验手机号

        // 判断账号是否重复
        if (!$this->isExistUser($user_data['account'])) {
            // 加密密码
            $user_data['password'] = Hash::make($user_data['password']);
            DB::transaction(function () use ($user_data) {
                $user = AdminUser::create($user_data);
                // 判断是否授权
                if ($this->isExist($user_data, 'role_ids')) {
                    $roles_ids = $user_data['role_ids'];
                    unset($user_data['role_ids']);
                    // 授权
                    $this->assignRoles($user, $roles_ids);
                }
            });
            return ['account' => $user_data['account']];
        }
        $this->throwBusinessException(info: '用户已存在');
    }

    /**
     * 更新用户数据
     * @param mixed $user
     * @param array $update_datas
     * @return mixed
     * @throws BusinessException
     * @throws \Throwable
     */
    public function updateUser(array $update_datas, array|Authenticatable $user = null): mixed
    {
        $this->isExistDepartment($update_datas);
        if ($user) {
            $this->emailUpdateCheck($user, $update_datas);
            $this->phoneUpdateCheck($user, $update_datas);
        }
        return DB::transaction(function () use ($user, $update_datas) {
            (!$user && $this->isExist($update_datas, 'id'))
                ? $user = AdminUser::findOrFail($update_datas['id'])
                : $this->throwBusinessException(info: '参数错误');

            // 判断是否授权
            if ($this->isExist($update_datas, 'role_ids')) {
                $this->assignRoles($user, $update_datas['role_ids']);
                unset($update_datas['role_ids']);
            }
            return $user->update($update_datas);
        });
    }
}
